#include "ImageProcessor.h"

/** @brief Creates mask using depth values
*   @param Mat &output, Mat &depth, int fgThreshold, int bgThreshold
*   @return
*
* Creates a binary image where pixels with values
* in depth image larger than foreground threshold and smaller
* than background threshold are 1, others 0.
*
*/
void ImageProcessor::createMaskFromDepth(Mat &output, Mat &depth, int fgThreshold, int bgThreshold){

    Mat fgMat(Size(640,480),CV_8UC1);
    Mat bgMat(Size(640,480),CV_8UC1);
    Mat element(Size(7,7), CV_8UC1);

    fgMat = (depth > fgThreshold); //Remove foreground
    bgMat = (depth < bgThreshold); //Remove background
    bitwise_and(fgMat,bgMat, output);//Combine into mask


    //GaussianBlur(output, output, Size(7,7), 5, 0, BORDER_DEFAULT); //Blur mask
    dilate(output, output, element, Point(-1, -1), 1, BORDER_CONSTANT,morphologyDefaultBorderValue());
}

/** @brief Get separated channels of image
*   @param Mat &original, vector<Mat> &channels
*   @return
*
* Stores separated image channels in output vector.
*
*/
void ImageProcessor::getChannels(Mat &original, vector<Mat> &channels){

    IplImage ipl = original;
	IplImage *ipoint;
	ipoint = &ipl;


	for(int i = 0; i< ipoint->nChannels;i++){
	    Mat m(Size(640,480),CV_8UC1,Scalar(0));
        channels.push_back(m);
	}

	split(original, channels);

}

/** @brief Combine channels into one image
*   @param vector<Mat> &original, Mat &output
*   @return
*
* Merge channels to one image.
*
*/
void ImageProcessor::getGrayscaleImg(vector<Mat> &original, Mat &output){

    int channels = original.size();
    Mat tmp(Size(640,480),CV_8UC1,Scalar(0));

	for(int i = 0; i< channels;i++){
        tmp = tmp + original[i]/channels;
	}

    output = tmp;

}

/** @brief Apply mask to image
*   @param Mat &mask, Mat &output
*   @return
*
* Apply mask by multiplication
*
*/
void ImageProcessor::applyMask(Mat &mask, Mat &output){

    output = output.mul(mask, 0.003921569);

}
